using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace MainGame.Utilities
{
  /// <summary>
  /// This is a game component that implements IUpdateable.
  /// </summary>
  public class TrialComponent : Microsoft.Xna.Framework.DrawableGameComponent
  {
    public bool trialExpired;
    float remainingTime;
    int numTries;
    SpriteBatch spriteBatch;
    Texture2D logo, whitePx;
    SpriteFont baveuse;

    public TrialComponent(Game game)
      : base(game)
    {
      spriteBatch = Game.GetContext().SpriteBatch;
      DrawOrder = 100;
      trialExpired = false;

      //ResetTime();
      
      Game.Services.AddService(typeof(TrialComponent), this);
      //LoadTime(Game, Game.Content.RootDirectory);
      LoadTime(Game, "");
      //if (remainingTime <= 0)
      numTries--;
      if(numTries < 0)
      {
        trialExpired = true;
        //remainingTime = 0;
      }
    }

    private void ResetTime()
    {
      //remainingTime = 30.0f;
      numTries = 3;
      //SaveTime(Game.Content.RootDirectory);
      SaveTime("");
      Game.Exit();
    }

    /// <summary>
    /// Allows the game component to perform any initialization it needs to before starting
    /// to run.  This is where it can query for any required services and load content.
    /// </summary>
    public override void Initialize()
    {
      baveuse = Game.Content.Load<SpriteFont>(@"baveuse_small");
      logo = Game.Content.Load<Texture2D>(@"Images//Menu//Logo");
      whitePx = Game.Content.Load<Texture2D>("white_pixel");
      base.Initialize();
    }

    protected override void Dispose(bool disposing)
    {
      //SaveTime(Game.Content.RootDirectory);
      SaveTime("");
      base.Dispose(disposing);
    }


    private void SaveTime(string dirPath)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(int));
      string saveFile = Path.Combine(dirPath, "mode.car");

#if WINDOWS || XBOX
      //if (!Directory.Exists(dirPath))
      //  // Create the directory
      //  Directory.CreateDirectory(dirPath);
      StreamWriter writer = new StreamWriter(saveFile);

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // Create the directory
      if (!appStorage.DirectoryExists(dirPath))
        appStorage.CreateDirectory(dirPath);
      if (appStorage.FileExists(saveFile))
        appStorage.DeleteFile(saveFile);
      IsolatedStorageFileStream streamFile = appStorage.OpenFile(saveFile, FileMode.OpenOrCreate);
      StreamWriter writer = new StreamWriter(streamFile);

#endif
      //serializer.Serialize(writer, (float)remainingTime);
      serializer.Serialize(writer, (int)numTries);
      writer.Close();
    }

    private void LoadTime(Game game, string dirPath)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(int));
      string saveFile = Path.Combine(dirPath, "mode.car");

      var content = @"<?xml version=""1.0"" encoding=""utf-8""?>
        <int>3</int>";

#if WINDOWS || XBOX
      // If there is no file saved, create it
      if (!File.Exists(saveFile))
      {
        using (StreamWriter filestream = new StreamWriter(File.Open(saveFile, FileMode.CreateNew)))
        {
          filestream.Write(content);
        }
      }
      using (var filestream = File.Open(saveFile, FileMode.OpenOrCreate))
      {
        //remainingTime = (float)serializer.Deserialize(filestream);
          numTries = (int)serializer.Deserialize(filestream);
      }

#else
      IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication();
      // If there is no file saved, create it
      if (!appStorage.FileExists(saveFile))
      {
        using (var filestream = new StreamWriter(appStorage.OpenFile(saveFile, FileMode.OpenOrCreate)))
        {
          filestream.Write(content);
        }
      }
      //using (var filestream = appStorage.OpenFile(saveFile, FileMode.OpenOrCreate))
      using (var filestream = appStorage.OpenFile(saveFile, FileMode.Open))
      {
        //remainingTime = (float)serializer.Deserialize(filestream);
        numTries = (int)serializer.Deserialize(filestream);
      }
#endif
    }

    /// <summary>
    /// Allows the game component to update itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    /// 

    
    float closeTimer = 5.0f;

    public override void Update(GameTime gameTime)
    {
      //remainingTime -= gameTime.dt();

      //if (remainingTime <= 0)
      //  trialExpired = true;

      if (numTries < 0)
        closeTimer -= gameTime.dt();

      //if (remainingTime <= 0)
      if(closeTimer <= 0)
      {
        Game.Exit();
      }

      if (trialExpired)
      {
        // Input: back button pressed
        if (((Game1)Game).IsBackButtonPressed())
        {
          Game.Exit();
        }
      }

      base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
      spriteBatch.Begin();
      if (trialExpired)
      {
        spriteBatch.Draw(whitePx, Game.GraphicsDevice.Viewport.Bounds, null, new Color(0, 0, 0, 220));
        spriteBatch.Draw(logo, new Rectangle(Game.GraphicsDevice.Viewport.Bounds.Center.X, Game.GraphicsDevice.Viewport.Bounds.Center.Y - 50, 160, 220), null, Color.White, 0.0f, new Vector2(logo.Bounds.Center.X, logo.Bounds.Center.Y), SpriteEffects.None, 0.0f);
        spriteBatch.DrawString(baveuse, Locale.Strings.TrialExpired, new Vector2(Game.GraphicsDevice.Viewport.Bounds.Center.X, Game.GraphicsDevice.Viewport.Bounds.Center.Y + 100), Color.Red, 0.0f, baveuse.MeasureString(Locale.Strings.TrialExpired) / 2, 1.5f, SpriteEffects.None, 1.0f);
      }
      else
      {
        var strLen = (int)(baveuse.MeasureString(Locale.Strings.TriesLeft).X);
        var rect = new Rectangle(105, 0, strLen + 10, 60);
        spriteBatch.Draw(whitePx, rect, null, new Color(220, 220, 220, 220), 0.0f, new Vector2(whitePx.Bounds.Center.X, whitePx.Bounds.Center.Y), SpriteEffects.None, 1.0f);
        TimeSpan elapsedTimeSpan = TimeSpan.FromSeconds((double)remainingTime);
        //string printedTime = elapsedTimeSpan.Minutes + ":" + elapsedTimeSpan.Seconds;
        string printedTime = " " + (numTries);
        //if (elapsedTimeSpan.Minutes < 10)
        //  printedTime = printedTime.Insert(0, "0");
        //if (elapsedTimeSpan.Seconds < 10)
        //  printedTime = printedTime.Insert(printedTime.Length - 1, "0");

        spriteBatch.DrawString(baveuse, Locale.Strings.TriesLeft, new Vector2(110, -5), Color.Red, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f);
        spriteBatch.DrawString(baveuse, printedTime, new Vector2(rect.Center.X, rect.Center.Y + 20), Color.Red, 0.0f, new Vector2(30, 25), 1.0f, SpriteEffects.None, 1.0f);
      }
      spriteBatch.End();

      base.Draw(gameTime);
    }
  }
}
